<script setup lang="ts">
import type { AreaPrickerConfig, optionsItem } from '@/types/pricker';
import { inject, reactive, watchEffect, watch, unref } from 'vue';

// 是否为大屏应用
const largenScreen = inject<boolean>('largenScreen');
// 是否为只读状态
const readOnly = inject<boolean>('readOnly', false);

interface Props {
  modelValue: [prov: string, area: string, district?: string] | [];
  label: string;
  name: string;
  columns: optionsItem[];
}
const props = withDefaults(defineProps<Props>(), {
  modelValue: () => [],
  columns: () => [],
  label: '',
  name: '',
});

const emit = defineEmits<{
  (e: 'update:model-value', value: optionsItem[]): void;
  (e: 'onConfirm', value: optionsItem[]): void;
}>();

const areaPricker: AreaPrickerConfig = reactive({
  show: false,
  cascaderValue: '',
  showValue: () => {
    const prov = areaPricker.columns.find((v) => v.value === props.modelValue[0]);
    const area = prov?.children?.find((v) => v.value === props.modelValue[1]);
    const district = area?.children?.find((v) => v.value === props.modelValue[2]);

    const arr: string[] = [];
    if (prov) {
      arr.push(prov.text);
    }
    if (area) {
      arr.push(area.text);
    }
    if (district) {
      arr.push(district.text);
    }
    return arr.join('-');
  },
  onConfirm({ selectedOptions }: { selectedOptions: optionsItem[] }) {
    emit('onConfirm', selectedOptions);
    areaPricker.show = false;
  },
  columns: props.columns,
});

watch(
  () => props.columns,
  () => {
    areaPricker.columns = props.columns;
  }
);

watchEffect(() => {
  areaPricker.cascaderValue = props.modelValue[2] || props.modelValue[1] || '';
});

const showPicker = () => {
  if (!unref(readOnly)) {
    areaPricker.show = true;
  }
};

defineExpose({
  setValue(value: string) {
    areaPricker.cascaderValue = value;
  },
});
</script>
<template>
  <van-field
    v-bind="$attrs"
    label-class="u_label"
    :model-value="areaPricker.showValue()"
    :is-link="!readOnly"
    readonly
    :name="name"
    :label="label"
    :placeholder="`点击选择${label}`"
    :rules="[{ required: true, message: `请选择${label}` }]"
    @click="showPicker"
  />

  <!-- 弹框 -->
  <van-popup
    v-model:show="areaPricker.show"
    round
    position="bottom"
    safe-area-inset-bottom
    :lock-scroll="!largenScreen"
  >
    <van-cascader
      v-model="areaPricker.cascaderValue"
      title="请选择所在地区"
      :options="areaPricker.columns"
      @close="areaPricker.show = false"
      @finish="areaPricker.onConfirm"
    />
  </van-popup>
</template>
<style lang="less" scoped></style>
